<template>
  <div class="task-list">
    <div class="list-header">
      <div class="header-title">任务列表</div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateTask">
          <el-icon><Plus /></el-icon>
          新建任务
        </el-button>
      </div>
    </div>

    <div class="list-content">
      <div class="filter-bar">
        <el-select v-model="filter.status" placeholder="状态" clearable size="default">
          <el-option label="全部" value="" />
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :value="option.value"
            :label="option.label"
          />
        </el-select>

        <el-select v-model="filter.priority" placeholder="优先级" clearable size="default">
          <el-option label="全部" value="" />
          <el-option
            v-for="option in priorityOptions"
            :key="option.value"
            :value="option.value"
            :label="option.label"
          />
        </el-select>

        <el-select v-model="filter.task_type" placeholder="任务类型" clearable size="default">
          <el-option label="全部" value="" />
          <el-option
            v-for="option in typeOptions"
            :key="option.value"
            :value="option.value"
            :label="option.label"
          />
        </el-select>

        <el-select v-model="filter.project_id" placeholder="所属项目" clearable size="default">
          <el-option label="全部" value="" />
          <el-option
            v-for="option in projectOptions"
            :key="option.value"
            :value="option.value"
            :label="option.label"
          />
        </el-select>

        <el-input
          v-model="filter.search"
          placeholder="搜索任务标题"
          clearable
          size="default"
          style="width: 200px;"
        />

        <el-button type="primary" size="default" @click="handleFilter">
          <el-icon><Search /></el-icon>
          筛选
        </el-button>
      </div>

      <div class="table-container">
        <el-table
          :data="tasks"
          size="default"
          border
          stripe
          style="width: 100%;"
        >
          <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="90">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" size="small">
                {{ getPriorityText(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="task_type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag type="info" size="small">
                {{ getTypeText(row.task_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="project_name" label="所属项目" width="150" show-overflow-tooltip />
          <el-table-column prop="assignee_name" label="负责人" width="140" show-overflow-tooltip>
            <template #default="{ row }">
              <UserDisplay
                v-if="row.assignee_id"
                :user-id="row.assignee_id"
                :user-name="row.assignee_name"
                :show-avatar="true"
                size="small"
              />
              <span v-else style="color: #909399;">未分配</span>
            </template>
          </el-table-column>
          <el-table-column prop="reporter_name" label="报告人" width="140" show-overflow-tooltip>
            <template #default="{ row }">
              <UserDisplay
                v-if="row.reporter_id"
                :user-id="row.reporter_id"
                :user-name="row.reporter_name"
                :show-avatar="true"
                size="small"
              />
              <span v-else style="color: #909399;">未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleViewTask(row.id)"
              >
                查看
              </el-button>
              <el-button
                link
                type="success"
                size="small"
                @click="handleEditTask(row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDeleteTask(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-bar">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 创建/编辑任务对话框 -->
    <CreateTask
      :visible="createTaskVisible"
      :current-user-id="currentUserId"
      :status-options="statusOptions"
      :priority-options="priorityOptions"
      :type-options="typeOptions"
      :project-options="projectOptions"
      :users="users"
      :common-tag-options="commonTagOptions"
      @update:visible="createTaskVisible = $event"
      @created="handleTaskCreated"
    />

    <!-- 任务详情对话框 -->
    <TaskDetail
      :visible="taskDetailVisible"
      :task-id="currentTaskId"
      @update:visible="taskDetailVisible = $event"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { Task, TaskStatus, TaskPriority, TaskType, TaskQueryParams } from '@/types/task'
import { useTaskAPI } from '@/api/task'
import { useStatusUtils } from '@/composables/useStatusUtils'
import { usePriorityUtils } from '@/composables/usePriorityUtils'
import CreateTask from './CreateTask.vue'
import TaskDetail from './TaskDetail.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

// Props
const props = defineProps<{
  currentUserId: string
  users: { id: string; name: string }[]
  statusOptions: { value: TaskStatus; label: string }[]
  priorityOptions: { value: TaskPriority; label: string }[]
  typeOptions: { value: TaskType; label: string }[]
  projectOptions: { value: string; label: string }[]
  commonTagOptions: string[]
}>()

// Emits
const emit = defineEmits<{
  'task-updated': [taskId: string]
  'task-deleted': [taskId: string]
}>()

// API
const taskAPI = useTaskAPI()

// Status and Priority Utilities
const { getStatusType, getStatusText } = useStatusUtils()
const { getPriorityType, getPriorityText } = usePriorityUtils()

// Data
const tasks = ref<Task[]>([])
const createTaskVisible = ref(false)
const taskDetailVisible = ref(false)
const currentTaskId = ref('')
const currentEditTask = ref<Task | null>(null)

// Filter
const filter = reactive<TaskQueryParams>({
  page: 1,
  size: 20,
  status: '',
  priority: '',
  task_type: '',
  project_id: '',
  search: ''
})

// Pagination
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// Methods
const loadTasks = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载任务列表中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const params: TaskQueryParams = {
      ...filter,
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    const response = await taskAPI.getTasks(params)
    if (response.success) {
      tasks.value = response.data.items || []
      pagination.total = response.data.total || 0
      ElMessage.success('任务列表加载成功')
    } else {
      ElMessage.error('任务列表加载失败: ' + (response.message || '未知错误'))
    }
  } catch (error: any) {
    ElMessage.error('任务列表加载失败: ' + (error.message || '网络错误'))
  } finally {
    loading.close()
  }
}

const handleCreateTask = () => {
  currentEditTask.value = null
  createTaskVisible.value = true
}

const handleEditTask = (task: Task) => {
  currentEditTask.value = task
  createTaskVisible.value = true
}

const handleViewTask = (taskId: string) => {
  currentTaskId.value = taskId
  taskDetailVisible.value = true
}

const handleDeleteTask = async (taskId: string) => {
  try {
    await taskAPI.deleteTask(taskId)
    ElMessage.success('任务删除成功')
    await loadTasks()
    emit('task-deleted', taskId)
  } catch (error: any) {
    ElMessage.error('任务删除失败: ' + (error.message || '未知错误'))
  }
}

const handleFilter = () => {
  pagination.currentPage = 1
  loadTasks()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadTasks()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadTasks()
}

const handleTaskCreated = (taskId: string) => {
  ElMessage.success('任务创建成功')
  loadTasks()
  emit('task-updated', taskId)
}

const getTypeText = (type: TaskType): string => {
  const option = props.typeOptions.find(opt => opt.value === type)
  return option?.label || type
}

// Lifecycle
onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #e8e8e8;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.list-content {
  flex: 1;
  overflow: auto;
  padding: 16px 0;
}

.filter-bar {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.table-container {
  height: calc(100% - 60px);
  overflow: auto;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 12px 0;
  border-top: 1px solid #e8e8e8;
}
</style>